#!encoding=utf8

import requests
import json
import csv
from copy import deepcopy

def requestslib(headers, url, method, data={}, params={}, language=None):
    '''请求接口
    '''
    if language == 'json':
        data=json.dumps(data)
        headers["Content-Type"] = "application/json"
    if params != {}:
        text_params = ''
        for k,v in params.items():
            text_params = text_params + f'{k}={v}&'
        url = f'{url}?{text_params}'

    response = requests.request(method.upper(), url, headers=headers, data=data)
    print(url)
    print(method.upper())
    print(headers)
    print(data)
    print(response.text)
    return response.text

def run_interface_test(name):
    '''读取test_data文件夹下 name.json 文件 
        1、生成postman collection，可以导入postman 执行接口测试
        2、生成 name.csv 测试用例及测试结果文件
    '''    
    # 定义headers测试用例
    err_headers = {
            "Content-Type字段不存在": False,
            "Content-Type字段值为空字符串": ""
        }
    # 定义参数测试用例
    err_tem = {
        "正常情况": True,
        "字段不存在": False,
        "字段值为null": None,
        "字段值为数字0": 0,
        "字段值为数字": 123456,
        "字段值为字母": "asdfghh",
        "字段值为空字符串": "",
        "字段值为特殊字符": "!@#$%^&"
    }

    collection_name = '{0}_temp'.format(name)
    collection_template = json.load(open('postman/collection.json', 'r'))
    folder_item_template = json.load(open('postman/folder_item.json', 'r'))
    request_item_template = json.load(open('postman/request_item.json', 'r'))
    collection = deepcopy(collection_template)
    collection["info"]["name"] = collection_name
    test_json = json.load(open('test_data/{0}.json'.format(name), 'r'))
    case_list = test_json['case_list']
    base_url = test_json['base_url']
    headers = test_json['headers']
    csv_datas = []
    case_no1 = 1
    for case in case_list:
        print(case)
        case_no2 = 1
        test_name = "{0}.{1}{2}".format(case_no1, case_no2, case['test_name'])
        test_api = case['test_api']
        method = case['method']
        language = case['language']
        test_data = case['test_data']
        test_fields = test_data.keys() 
        folder_item = deepcopy(folder_item_template)
        folder_item['name'] = test_name
        # 参数校验
        for field in test_fields:
            for key,value in err_tem.items():
                request_item = deepcopy(request_item_template)
                csv_data = []
                test_name = "{0}.{1}{2}".format(case_no1, case_no2, case['test_name'])
                csv_data.append(test_name)
                csv_data.append(test_api)
                csv_data.append('参数校验')
                field_case_name = '{0}{1}'.format(field, key)
                request_item['name'] = field_case_name
                request_item['request']['method'] = method
                field_test_data = deepcopy(test_data)
                if key == "正常情况":
                    pass
                elif key == "字段不存在":
                    del field_test_data[field]
                else:
                    field_test_data[field] = value
                
                request_item['request']['body']['raw'] = json.dumps(field_test_data)
                url_raw = base_url + test_api
                request_item['request']['url']['raw'] = url_raw
                request_item['request']['url']['protocol'] = url_raw.split("://")[0]
                test_url_temp = url_raw.split("://")[1]
                host_temp = test_url_temp.split("/")[0]
                api_temp = test_url_temp.split("/")[1:]
                request_item['request']['url']['host'] = host_temp.split('.')
                request_item['request']['url']['path'] = api_temp
                folder_item['item'].append(request_item)
                # 执行接口测试
                requests_params = {}
                requests_data = {}
                if method.upper() == "GET":
                    requests_params = field_test_data
                    del request_item['request']['body']
                    request_item['request']['url']['raw'] = f'{url_raw}?{requests_params}'
                    query = []
                    d = {
							"key": "asdf",
							"value": "123"
						}
                    for k,v in requests_params.items():
                        d['key'] = k
                        d['value'] = v
                        query.append(deepcopy(d))
                    request_item['request']['url']['query'] = query
                elif method.upper() == "POST":
                    requests_data = field_test_data

                test_headers = deepcopy(headers)
                res = requestslib(test_headers, base_url + test_api, method, data=requests_data, language=language, params=requests_params)
                csv_data.append(field_case_name) 
                csv_data.append(res)
                csv_data.append(json.dumps(field_test_data))
                print(csv_data)
                csv_datas.append(csv_data)
                case_no2 = case_no2 + 1

        # headers 校验
        for key,value in err_headers.items():
            csv_data = []
            test_name = "{0}.{1}{2}".format(case_no1, case_no2, case['test_name'])
            csv_data.append(test_name)
            csv_data.append(test_api)
            csv_data.append('headers校验')
            test_headers = deepcopy(headers)
            if key == "Content-Type字段不存在":
                del test_headers['Content-Type']
            else:
                test_headers['Content-Type'] = value
            # 执行接口测试
            requests_params = {}
            requests_data = {}
            if method.upper() == "GET":
                requests_params = test_data
            elif method.upper() == "POST":
                requests_data = test_data

            res = requestslib(test_headers, base_url + test_api, method, data=requests_data, language=language, params=requests_params)
            csv_data.append(key) 
            csv_data.append(res)
            csv_data.append(json.dumps(test_data))
            print(csv_data)
            csv_datas.append(csv_data)
            case_no2 = case_no2 + 1
        
        collection['item'][0]['item'].append(folder_item)
        case_no1 = case_no1 + 1

    # 生成测试报告csv
    with open('testcase/{0}.csv'.format(name), 'w') as fp:
        f_csv = csv.writer(fp)
        f_csv.writerows(csv_datas)
    
    # 生成postmancollection
    json.dump(collection, open('./testcase/{0}_postman.json'.format(name), 'w'))


if __name__=='__main__':
    test_name = "baidu"
    run_interface_test(test_name)








